//
// Created by lz on 3/6/21.
//

#ifndef MYWEBLIB_NET_EVENTLOOPTHREADPOOL_H_
#define MYWEBLIB_NET_EVENTLOOPTHREADPOOL_H_

#include "base/noncopyable.h"
#include "base/Types.h"

#include <functional>
#include <memory>
#include <vector>

namespace lzweb
{
	namespace net
	{
		class EventLoop;
		class EventLoopThread;

		class EventLoopThreadPool : noncopyable
		{
		 public:
			using ThreadInitCallback = std::function<void (EventLoop* )>;

			EventLoopThreadPool(EventLoop* baseLoop, const string& nameArg);
			~EventLoopThreadPool();

			void setThreadNum(int numThreads) { numThreads_ = numThreads;}

			void start(const ThreadInitCallback& cb = ThreadInitCallback());

			// valid after calling start()
			/// round-robin
			EventLoop* getNextLoop();

			/// with the same hash code, it will always return the same EventLoop
			EventLoop* getLoopForHash(size_t hashCode);

			std::vector<EventLoop*> getAllLoops();

			bool started() const
			{
				return started_;
			}
			const string& name() const
			{ return name_; }




		 private:
			EventLoop* baseLoop_;  // 应该是线程池的主线程的loop,其运行loop不由该类负责
			string name_;   // 线程池的名字
			bool started_;  // 标记started_
			int numThreads_; // 设置的线程池数目
			int next_;   //用于getNextLoop()，标记下个应该分配任务的EventLoop
			std::vector<std::unique_ptr<EventLoopThread>> threads_;  // 通过用unique_ptr管理新建的线程
			std::vector<EventLoop* > loops_;  // 对应每个新线程运行的loop
		};
	} // namespace net
} // namespace lzweb


#endif //MYWEBLIB_NET_EVENTLOOPTHREADPOOL_H_
